<script setup lang="ts">

import { onMounted, ref } from 'vue'
import {
  UserQueryCriteria,
  UserVo,
  DikeQueryCriteria,
  PageDike,
  Dike,
  type Article,
  type ArticleQueryCriteria, type ArticleItemQueryCriteria, type ArticleItem,
} from '/@/api/openapi'
import { useUserStore } from '/@/store'
import type { UploadFile, UploadFiles, UploadProps, UploadRawFile } from 'element-plus'
import { ArticleService } from '/@/api/openapi'

const tableRef = ref()
const searchParams = ref<ArticleItemQueryCriteria>({
  pageNum: 1,
  pageSize: 5,
  pid: 0,
})

// 接收
import { useRoute } from 'vue-router'
import { toRefs } from 'vue'

const route = useRoute()
const { query } = toRefs(route)

const id = ref<Number>()

searchParams.value.pid = query.value.id
id.value = query.value.id

console.log('点击了Item')
console.log(query.value.id)

const article = ref<Article>({
  title: '测试',
})
ArticleService.queryArticleById({
  uid: query.value.id,
}).then((res) => {
  if (res.code === 200 && res.data !== undefined) {
    ElMessage.success(res.message)
    article.value = res.data
  } else {
    ElMessage.error(res.message)
  }

}, (error) => {
  ElMessage.error(error)
})

const total = ref<number>(0)
const store = useUserStore()

onMounted(() => {
  loadData()
  // if (store.isSign) {
  //   loadData()
  // }
})

import { DikeService } from '/@/api/openapi'
import { ElMessage, genFileId, UploadInstance, UploadUserFile } from 'element-plus'
import { base64ConvertFile, convertFileToBase64 } from '/@/utils/convert'
import { Search } from '@element-plus/icons-vue'

const tableData = ref<Array<ArticleItem>>()
const loadData = () => {
  console.log('点击了loadData')
  ArticleService.queryArticleItemAll(searchParams.value).then((res) => {
    console.log(res)
    ElMessage.success(res)
    if (res.code === 200 && res.data !== null) {
      tableData.value = res.data
    }
  }, (error) => {
    ElMessage.error(error)
  }).catch((error) => {
    ElMessage.error(error)
  })
}


const handleCurrentChange = (val: number) => {
  searchParams.value.pageNum = val
  loadData()
}

const editData = ref<ArticleItem>({
  pid: id,
  url: '',
  content: '',
})

const editDialogVisible = ref<boolean>(false)
const editUid = ref<number>(-1)
const editVisible = (data: any) => {
  // 选择编辑按钮
  editData.value = data
  editDialogVisible.value = true
}
const update_success = (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  console.log('新增-url成功')
  console.log(response)
  editData.value.url = response.data
}
const update_submit = async () => {
  console.log('开始修改')
  console.log(editData.value)
  if (editData.value.url === null || editData.value.url === undefined || editData.value.url === '') {
    ElMessage.error('图片还未上传')
    return
  }
  if (editData.value.content === null || editData.value.content === undefined) {
    ElMessage.error('文章标题未填写')
    return
  }
  ArticleService.updateArticleItem(editData.value).then((res) => {
    if (res.code === 200) {
      ElMessage.success(res.message)
      loadData()
    }
  }, (error) => {
    console.log('reject错误')
    ElMessage.error('错误')
  }).catch((error) => {
    console.log('错误')
    ElMessage.error(error)
  }).finally(() => {
    editDialogVisible.value = false
  })
}


const add_success = (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  console.log('新增-url成功')
  console.log(response)
  addData.value.url = response.data
}

const currentArticleId = ref<number>(-1)
const deleteDialogVisible = ref<boolean>(false)
const deleteVisible = (data: any) => {
  // 选择了删除按钮
  currentArticleId.value = data.id
  deleteDialogVisible.value = true
}

const deleteArticle = () => {
  if (currentArticleId.value === -1) {
    ElMessage.error('请先选择文章合集')
  }
  ArticleService.deleteArticleItem(currentArticleId.value).then((res) => {
    if (res.code === 200) {
      ElMessage.success(res.message)
    } else {
      ElMessage.error(res.message)
    }
    loadData()
  }, (error) => {
    ElMessage.error(error)
  }).catch((error) => {
    ElMessage.error(error)
  }).finally(() => {
    deleteDialogVisible.value = false
  })
}

const upload = ref<UploadInstance>()
const on_exceed = async (files: File[], uploadFiles: UploadUserFile[]) => {
  console.log('当超出限制时，执行的钩子函数')
  ElMessage.error('只能上传一张图片,请先删除原文件')
}

const choose = ref<number>(1)


// 下面是新增
const addDialogVisible = ref<boolean>(false)
const addData = ref<ArticleItem>({
  pid: id,
  url: '',
  content: '',
})
const addVisible = () => {
  // 选择新增按钮
  addDialogVisible.value = true
}
// 点击提交按钮
const add_submit = async () => {
  console.log('开始上传')
  console.log(addData.value)
  if (addData.value.url === null || addData.value.url === undefined || addData.value.url === '') {
    ElMessage.error('图片还未上传')
    return
  }
  if (addData.value.content === null || addData.value.content === undefined) {
    ElMessage.error('文章标题未填写')
    return
  }
  ArticleService.addArticleItem(addData.value).then((res) => {
    if (res.code === 200) {
      ElMessage.success(res.message)
      loadData()
    }
  }, (error) => {
    console.log('reject错误')
    ElMessage.error('错误')
  }).catch((error) => {
    console.log('错误')
    ElMessage.error(error)
  }).finally(() => {
    addDialogVisible.value = false
  })
}
</script>

<template>
  <div class="dike">
    <el-row>
      <el-col :span="4" :offset="5" class="grid-cell">
        <el-button type="info" @click="loadData" class="flesh">刷新</el-button>
        <el-button type="primary" @click="addVisible" class="flesh">新增</el-button>
      </el-col>
      <el-col :span="7" class="grid-cell">
        <div>
          {{ article.title }}
        </div>
      </el-col>
      <el-col :span="4" class="grid-cell">
        <el-input
          v-model="searchParams.content"
          placeholder="搜索文章名称"
          class="input-with-select"
        >
          <template #append>
            <el-button @click="loadData" :icon="Search" />
          </template>
        </el-input>
      </el-col>
    </el-row>


    <el-table class="table" border height="600" max-height="600" :ref="tableRef" :data="tableData" style="width: 60%">
      <el-table-column label="文章图片" width="180">
        <template #default="scope">
          <el-image
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            style="width: 200px; height: 150px"
            fit="cover"
            :src="scope.row.url" />
        </template>
      </el-table-column>
      <el-table-column prop="content" label="文章内容" width="250" />

      <el-table-column fixed="right" label="操作">
        <template #default="scope">
          <div class="option">
            <el-button type="primary" size="small" @click.prevent="editVisible(scope.row)">编辑文章
            </el-button>
            <el-button link type="primary" size="small" @click.prevent="deleteVisible(scope.row)">删除文章
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!--    <div class="pager-wrapper">-->
    <!--      <el-pagination-->
    <!--        background-->
    <!--        layout="prev, pager, next, jumper"-->
    <!--        :total="total"-->
    <!--        :page-size="searchParams.pageSize"-->
    <!--        :current-page="searchParams.pageNum"-->
    <!--        @current-change="handleCurrentChange"-->
    <!--      />-->
    <!--    </div>-->

    <!--    -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="提示"
      width="30%"
      align-center
    >
      <span>是否删除该文章合集</span>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="deleteArticle">
          确认
        </el-button>
      </span>
      </template>
    </el-dialog>


    <el-dialog
      v-model="addDialogVisible"
      title="新增文章"
      width="30%"
      align-center
    >
      <el-form :model="addData" ref="vForm" label-position="left" label-width="100px"
               size="default" @submit.prevent>
        <el-form-item label="图片" prop="longitude">
          <el-input v-model="addData.content" type="text" clearable></el-input>
        </el-form-item>
        <el-form-item label="文章图片" prop="image">
          <el-upload
            ref="upload"
            :on-success="add_success"
            :on-exceed="on_exceed"
            show-file-list
            drag
            action="https://wechat.xiaowang.link/oss/upload"
            :limit="1">
            <el-icon class="el-icon--upload">
              <upload-filled />
            </el-icon>
            <div class="el-upload__text">
              拖拽文件 or <em>点击文件</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                jpg/png files with a size less than 500kb
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-row>
          <el-col :offset="6" :span="4" class="grid-cell">
            <div class="static-content-item">
              <el-button @click="add_submit" type="primary">确认</el-button>
            </div>
          </el-col>
          <el-col :span="4" class="grid-cell">
            <div class="static-content-item">
              <el-button>重置</el-button>
            </div>
          </el-col>
        </el-row>

      </el-form>

    </el-dialog>


    <el-dialog
      v-model="editDialogVisible"
      title="修改文章"
      width="40%"
      align-center
    >
      <el-form :model="editData" ref="vForm" label-position="left" label-width="100px"
               size="default" @submit.prevent>
        <el-form-item label="图片" prop="longitude">
          <el-input v-model="editData.content" type="text" clearable></el-input>
        </el-form-item>
        <el-form-item label="文章图片" prop="image">
          <el-upload
            ref="upload"
            :on-success="update_success"
            :on-exceed="on_exceed"
            show-file-list
            drag
            action="https://wechat.xiaowang.link/oss/upload"
            :limit="1">
            <el-icon class="el-icon--upload">
              <upload-filled />
            </el-icon>
            <div class="el-upload__text">
              拖拽文件 or <em>点击文件</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                jpg/png files with a size less than 500kb
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-row>
          <el-col :offset="6" :span="4" class="grid-cell">
            <div class="static-content-item">
              <el-button @click="update_submit" type="primary">确认</el-button>
            </div>
          </el-col>
          <el-col :span="4" class="grid-cell">
            <div class="static-content-item">
              <el-button>重置</el-button>
            </div>
          </el-col>
        </el-row>

      </el-form>

    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.dike {
  padding: 30px;
  overflow: auto;

  .flesh {
    margin-bottom: 20px;
  }

  .pager-wrapper {
    margin-top: 10px;
  }

  .table {
    margin: 0 auto;
  }

}
</style>